package cn.geckos.ioc.factory
{
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import mx.utils.ObjectUtil;
	
	import cn.geckos.ioc.parsing.IParser;
	import cn.geckos.ioc.parsing.Scope;
	
	public class DefaultBeanFactory implements IBeanFactory
	{
		private var parser:IParser;
		private var objs:Dictionary;
		
		public function DefaultBeanFactory(parser:IParser)
		{
			this.parser = parser;
			this.objs = this.parser.parse();
			init();
		}
		
		public function init():void
		{
			for(var i:Object in objs)
			{
				if(objs[i].scope == Scope.SINGLETON)
				{
					extensionWeave(objs[i].object);
				}
			}
		}
		
		public function destroy():void
		{
			
		}
		
		public function getScope(name:String):String
		{
			var o:Bean = this.objs[name] as Bean;
			return o.scope;
		}
		
		public function isSingleton(name:String):Boolean
		{
			if(getScope(name) == Scope.SINGLETON) return true;
			else return false;
		}
		
		public function getBean(name:String):*
		{
			var o:Object = this.parser.getBean(name);
			if(this.objs[name].scope == Scope.PROTOTYPE)
				extensionWeave(o);
			return o;
		}
		
		public function getType(name:String):Class
		{
			var o:Bean = this.objs[name] as Bean;
			return getDefinitionByName(o.name) as Class;
		}
		
		protected function extensionWeave(o:Object):void
		{
			if(o is BeanFactoryAware)
			{
				o = o as BeanFactoryAware;
				o.setFactory(this);
			}
		}
	}
}